//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import { Button, message, Modal, Space, Table, Tag } from "antd";
import { open as shell_open } from '@tauri-apps/api/shell';
import type { TrigerMsgInfo } from "@/api/project_triger";
import { list_msg } from "@/api/project_triger";
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import moment from "moment";
import CodeEditor from '@uiw/react-textarea-code-editor';
import { writeText } from "@tauri-apps/api/clipboard";

const PAGE_SIZE = 10;

interface AttrItemProps {
    attr: string;
}


const AttrItem = (props: AttrItemProps) => {

    const [attrKey, setAttrKey] = useState("");
    const [attrValue, setAttrValue] = useState("");

    useEffect(() => {
        const parts = props.attr.split("=", 2);
        if (parts.length == 2) {
            setAttrKey(parts[0]);
            setAttrValue(parts[1]);
        }
    }, []);

    return (
        <Tag style={{ fontWeight: ["git.hookType"].includes(attrKey) ? 700 : 400 }}>
            {attrKey}=
            <>
                {(attrValue.startsWith("http://") || attrValue.startsWith("https://")) &&
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open(attrValue);
                    }} style={{ color: "blue" }}>{attrValue}</a>
                }
                {(attrValue.startsWith("http://") || attrValue.startsWith("https://")) == false && attrValue}
            </>
        </Tag>
    );
};

const TrigerDetail = () => {
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');

    const [msgList, setMsgList] = useState<TrigerMsgInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const [detailMsgInfo, setDetailMsgInfo] = useState<TrigerMsgInfo | null>(null);

    const loadMsgList = async () => {
        if (projectStore.projectHome.curTriger == null) {
            return;
        }
        const res = await request(list_msg({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            triger_id: projectStore.projectHome.curTriger.triger_id,
            filter_by_attr: false,
            attr_list: [],
            offset: PAGE_SIZE * curPage,
            limit: PAGE_SIZE,
        }));
        setTotalCount(res.total_count);
        setMsgList(res.msg_list);
    };

    const msgColumns: ColumnsType<TrigerMsgInfo> = [
        {
            title: "时间",
            width: 150,
            render: (_, row: TrigerMsgInfo) => moment(row.time_stamp).format("YYYY-MM-DD HH:mm:ss"),
        },
        {
            title: "事件属性",
            width: 350,
            render: (_, row: TrigerMsgInfo) => (
                <Space style={{ flexWrap: "wrap", overflowX: "hidden" }}>
                    {row.attr_list.map(attr => (
                        <AttrItem key={attr} attr={attr} />
                    ))}
                </Space>
            ),
        },
        {
            title: "操作",
            width: 100,
            render: (_, row: TrigerMsgInfo) => (
                <Space>
                    <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setDetailMsgInfo(row);
                        }}>查看原始数据</Button>
                </Space>
            ),
        },
    ];

    useEffect(() => {
        if (projectStore.projectHome.curTriger != null) {
            loadMsgList();
        }
    }, [projectStore.projectHome.curTriger?.triger_id, curPage]);

    return (
        <>
            <div style={{ height: "calc(100vh - 150px)", overflowY: "scroll",paddingLeft:"10px" }}>
                <Table rowKey="" dataSource={msgList} columns={msgColumns}
                    pagination={{ total: totalCount, pageSize: PAGE_SIZE, current: curPage + 1, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }} />
            </div>
            {detailMsgInfo != null && (
                <Modal open title="原始数据" footer={null} mask={false}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setDetailMsgInfo(null);
                    }}>
                    <CodeEditor
                        language="json"
                        value={(new TextDecoder('utf-8')).decode(Uint8Array.from(detailMsgInfo.content))}
                        style={{
                            maxHeight: "calc(100vh - 300px)",
                            overflowY: "scroll"
                        }}
                    />
                    <div style={{ display: "flex", justifyContent: "flex-end" }}>
                        <Button type="link" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const conent = (new TextDecoder('utf-8')).decode(Uint8Array.from(detailMsgInfo.content));
                            writeText(conent);
                            message.info("复制成功");
                        }}>复制内容</Button>
                    </div>
                </Modal>
            )}
        </>
    );
};

export default observer(TrigerDetail);